<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="isAll"/> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <my-table />
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{totalPrice}}
          </td>
        </tr>
      </tfoot>
    </table>
    <input type="text" placeholder="商品名称" v-model.trim="newItem.name" />
    <input type="number" placeholder="商品价格" v-model.trim.number="newItem.price" />
    <button @click="onAddItem">添加</button>
  </div>
</template>

<script>
import MyTable from '@/components/MyTable.vue'
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  components: { MyTable },
  data () {
    return {
      newItem: {
        name: '',
        price: null,
        num: 1,
        checked: false
      }
    }
  },
  computed: {
    ...mapState(['goodList']),
    ...mapGetters(['totalPrice']),
    // isAll () {
    //   return this.goodList.every((item) => {
    //     return item.checked
    //   })
    // },
    isAll: {
      get () {
        return this.goodList.every((item) => {
          return item.checked
        })
      },
      set (val) {
        this.goodList.forEach((item) => {
          item.checked = val
        })
      }
    }
  },
  methods: {
    ...mapMutations(['addItem']),
    onAddItem () {
      // console.log(newItem)
      // this.newItem.name = this.nameValue
      // this.newItem.price = this.priceValue
      // if (this.newItem.name !== '' && this.newItem.price !== '' && this.newItem.price > 0) {
      //   this.addItem(this.newItem)
      // }

      if (this.newItem.name !== '' && this.newItem.price !== '' && this.newItem.price > 0) {
        const obj2 = JSON.parse(JSON.stringify(this.newItem)) // 可行
        this.addItem(obj2)
        this.newItem.name = ''
        this.newItem.price = null
      }

      // const obj2 = { // 可行
      //   name: this.newItem.name,
      //   price: this.newItem.price,
      //   num: 0,
      //   checked: this.newItem.checked
      // }
      // this.addItem(obj2)
    }
  }
}
</script>

<style>
/* 清理数字输入框的默认样式 */
input::-webkit-outer-spin-button,input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
</style>
